import {
    GET_FILE_URL,
    getAppId,
    getAppList,
} from "@/api/login/login";
import getRequest from "@/server/getRequest";
import {
    searchFilesList,
    downFile
} from '@/utils/getFiles';


const changeBg = (type, data) => {
    //对应的标签id
    const bgMap = {
        sysBg: "MainBackgroundArea",
    };
    if (type in bgMap) {
        const eles = document.querySelectorAll(`#${bgMap[type]}`);
        eles.forEach((ele) => {
            ele.style.backgroundImage = `url(${data})`;
        });
    }
};

const state = {
    upPic: {
        sysLogo: {
            pic: "",
            id: "S0001",
            name: "sysLogo",
        },
        sysBg: {
            pic: "",
            id: "S0002",
            name: "sysBg",
        },
        sysLogoMain: {
            pic: "",
            id: "S0006",
            name: "sysLogoMain",
        },
        sysTheFontAfterLogo: {
            pic: "",
            id: "S0007",
            name: "sysTheFontAfterLogo",
        },
        sysLabel: {
            pic: "",
            id: "S0008",
            name: "sysLabel",
        },
    },
    mainIconUrl: '',
    appName: '',
};

const mutations = {
    setUpPic: (state, {
        key,
        res
    }) => {
        state.upPic[key].pic = res;
    },
    setAppName: (state, name) => {
        state.appName = name;
        document.title = name;
    },
    setMainIconUrl: (state, url) => {
        state.mainIconUrl = url;
        const link = document.querySelector('link[rel="icon"]');
        link && (link.href = url);
    }
};

const actions = {
    getAppName: async ({
                           commit
                       }, appId) => {
        const appListRequest = await getAppList({});
        if (appListRequest.success) {
            const appNow = appListRequest.data.find(
                (item) => {
                    return item.appId === appId + "" || item.appId === appId * 1;
                }
            );
            if (appNow) {
                commit('setAppName', appNow.appName);
            }
        }
    },
    getFiles: async ({
                         commit,
                         state,
                         dispatch
                     }) => {
        const {
            href
        } = location;
        const resu = href.match(/\/\w+\/#/);

        let appName; //package name
        if (state.upPic.sysLogo.pic !== '') {
            return
        }
        if (resu) {
            const appName1 = resu && resu[0].match(/\w+/);
            appName = appName1 && appName1[0];
        }

        if (appName) {
            const packageName = appName;
            const {
                data: appId
            } = await getAppId({
                position: packageName
            });
            if (appId) {
                // localStorage.setItem('appId', appId);//保存appId会导致结转bug
                if (state.appName === "") {
                    dispatch('getAppName', appId);
                }

                for (const key in state.upPic) {
                    const localRes = sessionStorage.getItem(key);
                    if (key === "sysLogoMain") {
                        const fileMainLogoUrl = sessionStorage.getItem(key + "Url");
                        fileMainLogoUrl && commit('setMainIconUrl', fileMainLogoUrl);
                    }
                    if (localRes) {
                        commit('setUpPic', {
                            key,
                            res: localRes
                        })
                        changeBg(key, localRes);
                    } else {
                        searchFilesList({
                            appId,
                            type: state.upPic[key].id,
                        }).then(async (fileInfo) => {
                            const data = fileInfo.data && fileInfo.data[0];
                            if (data) {
                                //todo 开始下载文件
                                downFile(data, "pic").then((res) => {
                                    sessionStorage.setItem(key, res);
                                    commit('setUpPic', {
                                        key,
                                        res
                                    })
                                    changeBg(key, res);
                                });
                                //todo 更换浏览器tab图标
                                if (key === "sysLogoMain") {
                                    const BASE_URL = await getRequest;
                                    const baseURL = BASE_URL?.data.ApiUrl;
                                    const fileMainLogoUrl = `${baseURL + GET_FILE_URL}?id=${
                                        data.id
                                    }&fileName=${data.saveName}`;
                                    commit('setMainIconUrl', fileMainLogoUrl)
                                    sessionStorage.setItem(key + "Url", fileMainLogoUrl);
                                }
                            }
                        })
                    }
                }
            }
        }
    }
};

export default {
    namespaced: true,
    state,
    mutations,
    actions
}
